package com.ruoyi.cms.blog.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cms.fileInfo.service.ISysFileInfoService;
import com.ruoyi.cms.tag.domain.CmsTag;
import com.ruoyi.cms.tag.service.ICmsTagService;
import com.ruoyi.cms.type.domain.CmsType;
import com.ruoyi.cms.type.service.ICmsTypeService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.constant.BusinessTypeEnum;
import com.ruoyi.cms.blog.domain.CmsBlog;
import com.ruoyi.cms.blog.service.ICmsBlogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 事件管理Controller
 *
 * @author ning
 * @date 2022-01-01
 */
@Slf4j
@RestController
@RequestMapping("/cms/blog")
public class CmsBlogController extends BaseController {
    @Autowired
    private ICmsBlogService cmsBlogService;

    @Autowired
    private ICmsTypeService cmsTypeService;

    @Autowired
    private ICmsTagService cmsTagService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysFileInfoService sysFileInfoService;


    /**
     * 首页查询文章列表
     */
    @GetMapping("/cms/cmsList")
    public TableDataInfo cmsList(CmsBlog cmsBlog) {
        startPage();
        //状态为发布
        cmsBlog.setStatus("1");
        cmsBlog.setCreateBy("");

        List<CmsBlog> list = cmsBlogService.selectCmsBlogList(cmsBlog);
        return getDataTable(list);
    }

    @GetMapping("/necessary")
    public AjaxResult getNecessaryData(){
        List<CmsTag> cmsTags = cmsTagService.selectCmsTagList(new CmsTag());

        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("cmsTags", cmsTags);

        List<CmsType> cmsTypes = cmsTypeService.selectCmsTypeList(new CmsType());
        ajaxResult.put("cmsTypes", cmsTypes);

        return ajaxResult;
    }

    /**
     * 首页获取文章详细信息
     */
    @GetMapping(value = {"/cms/detail/", "/cms/detail/{id}"})
    public AjaxResult getInfoDetail(@PathVariable(value = "id", required = false) Long id) {
        AjaxResult ajax = AjaxResult.success();
        CmsType cmsType = new CmsType();
        CmsTag cmsTag = new CmsTag();
        List<CmsType> typeList = cmsTypeService.selectCmsTypeList(cmsType);
        if (!typeList.isEmpty()) {
            ajax.put("types", typeList);
        }
        List<CmsTag> tagList = cmsTagService.selectCmsTagList(cmsTag);
        if (!tagList.isEmpty()) {
            ajax.put("tags", tagList);
        }
        if (StringUtils.isNotNull(id))
        {
            CmsBlog cmsBlog = cmsBlogService.selectCmsBlogById(id);
            if (cmsBlog != null) {
                ajax.put(AjaxResult.DATA_TAG, cmsBlog);
            }
            else {
                ajax.put(AjaxResult.DATA_TAG, "");
            }
        }
        return ajax;
    }

    /**
     * 首页按分类查询文章列表
     */
    @GetMapping("/cms/cmsListByType/{id}")
    public TableDataInfo cmsListByTypeId(@PathVariable(value = "id", required = false) Long id) {
//        List<CmsBlog> list1 = cmsBlogService.selectCmsBlogListByTypeIdStep1(id);
        startPage();
        List<CmsBlog> list = cmsBlogService.selectCmsBlogListByTypeId(id);
//        List<CmsBlog> list = cmsBlogService.selectCmsBlogListByTypeIdStep2(list1);
        return getDataTable(list);
    }

    /**
     * 首页按标签查询文章列表
     */
    @GetMapping("/cms/cmsListByTag/{id}")
    public TableDataInfo cmsListByTagId(@PathVariable(value = "id", required = false) Long id) {
//        List<CmsBlog> list1 = cmsBlogService.selectCmsBlogListByTagIdStep1(id);
        startPage();
        List<CmsBlog> list = cmsBlogService.selectCmsBlogListByTagId(id);
//        List<CmsBlog> list = cmsBlogService.selectCmsBlogListByTagIdStep2(list1);
        return getDataTable(list);
    }

    /**
     * 首页查询推荐文章列表
     */
    @GetMapping("/cms/cmsListRecommend")
    public TableDataInfo cmsListRecommend(CmsBlog cmsBlog) {
        startPage();
        //状态为发布
        cmsBlog.setStatus("1");
        cmsBlog.setCreateBy("");
        List<CmsBlog> list = cmsBlogService.selectCmsBlogListRecommend(cmsBlog);
        return getDataTable(list);
    }

    /**
     * 首页增加阅读量
     */
    @GetMapping("/cms/addBlogViews/{id}")
    public AjaxResult addBlogViews(@PathVariable(value = "id", required = false) Long id) {
        CmsBlog cmsBlog = cmsBlogService.selectCmsBlogById(id);
        Long views = cmsBlog.getViews();
        views += Long.parseLong("1");
        cmsBlog.setViews(views);
        cmsBlogService.updateCmsBlog(cmsBlog);
        return AjaxResult.success(id);
    }

    /**
     * 随笔页查询文章列表
     */
    @GetMapping("/cms/cmsEssayList")
    public TableDataInfo cmsEssayList(CmsBlog cmsBlog) {
        startPage();
        //状态为发布
        cmsBlog.setStatus("1");
        List<CmsBlog> list = cmsBlogService.selectCmsBlogList(cmsBlog);
        return getDataTable(list);
    }

    /**
     * 查询事件管理列表
     */
//    @PreAuthorize("@ss.hasPermi('cms:blog:list')")
    @GetMapping("/list")
    public TableDataInfo list(CmsBlog cmsBlog) {
        startPage();
        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(getLoginUser().getUser());

//        if (SecurityUtils.isAdmin(getUserId()) && (roles.contains("admin") || roles.contains("admin2"))) {
//            cmsBlog.setCreateBy("");
//        }

//        log.info("数据判断条件1:{},条件2:{}", SecurityUtils.isAdmin(getUserId()),roles.contains("admin"));
        List<CmsBlog> list = cmsBlogService.selectCmsBlogList(cmsBlog);
        return getDataTable(list);
    }

    /**
     * 导出事件管理列表
     */
    @PreAuthorize("@ss.hasPermi('cms:blog:export')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmsBlog cmsBlog) {
        List<CmsBlog> list = cmsBlogService.selectCmsBlogList(cmsBlog);
        ExcelUtil<CmsBlog> util = new ExcelUtil<>(CmsBlog.class);
        util.exportExcel(response, list, "事件管理数据");
    }

    /**
     * 获取事件管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('cms:blog:query')")
    @GetMapping(value = {"/", "/{id}"})
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id) {
        AjaxResult ajax = AjaxResult.success();
        CmsType cmsType = new CmsType();
        CmsTag cmsTag = new CmsTag();
        ajax.put("types", cmsTypeService.selectCmsTypeList(cmsType));
        ajax.put("tags", cmsTagService.selectCmsTagList(cmsTag));
        if (StringUtils.isNotNull(id)) {
            ajax.put(AjaxResult.DATA_TAG, cmsBlogService.selectCmsBlogById(id));
        }
        return ajax;
    }

    /**
     * 新增事件管理
     */
    @PreAuthorize("@ss.hasPermi('cms:blog:add')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmsBlog cmsBlog) {
        cmsBlog.setCreateBy(getUsername());
        cmsBlog.setCreateId(getUserId());
        String studentAvatar = cmsBlogService.getStudentAvatar(cmsBlog);
        if (studentAvatar != null && !studentAvatar.isEmpty()) {
            cmsBlog.setBlogPic(studentAvatar);
            cmsBlog.setBlogPicType("1");
        }
        Long blogId = cmsBlogService.insertCmsBlog(cmsBlog);
        return AjaxResult.success(blogId);
    }

    /**
     * 修改事件管理
     */
    @PreAuthorize("@ss.hasPermi('cms:blog:edit')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmsBlog cmsBlog) {
        cmsBlog.setUpdateBy(getUsername());
        //删除原首图
        CmsBlog oldBlog = cmsBlogService.selectCmsBlogById(cmsBlog.getId());
        if (cmsBlog.getBlogPic().isEmpty() || !cmsBlog.getBlogPic().equals(oldBlog.getBlogPic())) {
            if (!oldBlog.getBlogPic().isEmpty()) {
                String blogPic = oldBlog.getBlogPic();
                int newFileNameSeparatorIndex = blogPic.lastIndexOf("/");
                String FileName = blogPic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                sysFileInfoService.deleteSysFileInfoByFileObjectName(FileName);
            }
        }
        return toAjax(cmsBlogService.updateCmsBlog(cmsBlog));
    }

    @PutMapping("/updateState/{id}")
    public AjaxResult editState(@PathVariable("id") String id) {
        int state = cmsBlogService.updateCmsState(id);
        log.info("更新ID为{}的状态为1",id);
        return AjaxResult.success(state);
    }

    @PutMapping("/updateState/{id}/{type}")
    public AjaxResult editState2(@PathVariable("id") int id,@PathVariable("type") int type) {
        int state = cmsBlogService.updateCmsState(id, type);
        log.info("更新ID为{}的状态为{}",id,type);
        return AjaxResult.success(state);
    }

    @PutMapping("/updateState")
    public AjaxResult editState3(@RequestBody CmsBlog cmsBlog) {
        int state = cmsBlogService.updateCmsState(cmsBlog);
        if (state == 0) {
            return AjaxResult.error("系统异常");
        }
        return AjaxResult.success(state);
    }

    /**
     * 删除事件管理
     */
    @PreAuthorize("@ss.hasPermi('cms:blog:remove')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        //删除原首图
        for (Long id : ids) {
            CmsBlog oldBlog = cmsBlogService.selectCmsBlogById(id);
            if (!oldBlog.getBlogPic().isEmpty()) {
                String blogPic = oldBlog.getBlogPic();
                int newFileNameSeparatorIndex = blogPic.lastIndexOf("/");
                String FileName = blogPic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                sysFileInfoService.deleteSysFileInfoByFileObjectName(FileName);
            }
        }
        return toAjax(cmsBlogService.deleteCmsBlogByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('cms:blog:remove')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/del/{ids}")
    public AjaxResult remove_delete(@PathVariable Long[] ids) {
        return toAjax(cmsBlogService.deleteCmsByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('cms:blog:remove')")
    @Log(title = "事件管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/del/{id}")
    public AjaxResult remove_del(@PathVariable Long id) {
        return toAjax(cmsBlogService.deleteCmsById(id));
    }

    /**
     * 取消按钮-删除首图
     */
    @PreAuthorize("@ss.hasPermi('cms:blog:edit')")
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestBody CmsBlog cmsBlog) {
        String blogPic = cmsBlog.getBlogPic();
        if (blogPic != null && !blogPic.isEmpty()) {
            Long blogId = cmsBlog.getId();
            if (blogId == null) {
                int newFileNameSeparatorIndex = blogPic.lastIndexOf("/");
                String FileName = blogPic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                sysFileInfoService.deleteSysFileInfoByFileObjectName(FileName);
            } else {
                String Pic = cmsBlogService.selectCmsBlogById(blogId).getBlogPic();
                if (!blogPic.equals(Pic)) {
                    int newFileNameSeparatorIndex = blogPic.lastIndexOf("/");
                    String FileName = blogPic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                    sysFileInfoService.deleteSysFileInfoByFileObjectName(FileName);
                }
            }
        }
        return toAjax(1);
    }
}
